<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import dayjs from 'dayjs'
import type { IConfig, IUserList } from '@/apis/types/user'
// defineOptions({ name: 'NewView' })
import { reqUserData, reqDeleteUser, reqAddUser, reqUpdateUser } from '@/apis/user'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 搜索name查询参数，分页page = 1, limit = 10
const config = reactive<IConfig>({
  name: '',
  page: 1,
  limit: 15
})
const tableCount = ref(0)
const tableData = ref<IUserList[]>([])
const getUserData = async () => {
  const res = await reqUserData(config)
  // console.log(res.data)
  tableCount.value = res.data.count
  tableData.value = res.data.list.map((item) => {
    return {
      ...item,
      age: dayjs().diff(item.birthday, 'year'),
      sex: item.sex === 1 ? '男' : '女'
    }
  })
}
const handleChange = (page: number) => {
  config.page = page
  getUserData()
}
const handleSizeChange = (size: number) => {
  config.limit = size
  config.page = 1
  getUserData()
}
// 编辑用户弹窗
let dataBak = {}
const handleEdit = (data: IUserList) => {
  dialogVisible.value = true
  action.value = 'edit'
  data.sex = data.sex === '男' ? 1 : 0
  nextTick() // 等待Dom渲染完成， 解决 新增 按钮 有老数据的问题
  Object.assign(formUser, data)
  dataBak = { ...formUser } // 备份数据 用于判断是否修改
}
const handleDelete = (data: IUserList) => {
  ElMessageBox.confirm('确认删除该用户吗？')
    .then(() => {
      reqDeleteUser({ id: data.id as string }).then(() => {
        getUserData()
        ElMessage.success('删除成功')
      })
    })
    .catch(() => {
      console.log('cancel')
    })
}
onMounted(() => {
  getUserData()
})

const dialogVisible = ref(false)
const userForm = ref<FormInstance>()

// 新增用户弹窗
const addUserHandler = () => {
  dialogVisible.value = true
  action.value = 'add'
}

const formUser = reactive({
  name: '',
  age: '',
  sex: 1,
  birthday: '',
  addr: ''
})
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 11, message: '长度在 2 到 11 个字符', trigger: 'blur' }
  ],
  age: [
    // { required: true, message: '请输入年龄', trigger: 'blur' },
    // { type: 'number', message: '请输入数字' }
    { type: 'number', required: true, trigger: 'blur', min: 1, max: 120, message: '请输入数字年龄[1-120]' }
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthday: [{ required: true, message: '请选择出生年月', trigger: 'change' }],
  addr: [
    { required: true, message: '请输入住址', trigger: 'blur' },
    { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
  ]
})
const action = ref('add')
// 关闭弹窗
const handleClose = (formEl: FormInstance | undefined) => {
  dialogVisible.value = false
  if (!formEl) return
  // 重置表单
  formEl.resetFields()
  action.value = ''
}
const timeFormat = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD')
}
// 表单提交
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      let res = null
      formUser.birthday = timeFormat(formUser.birthday)
      if (action.value === 'add') {
        // 新增用户
        res = await reqAddUser(formUser)
      } else {
        // 编辑用户
        // 判断未修改 不发送修改请求
        if (JSON.stringify(dataBak) === JSON.stringify(formUser)) {
          ElMessage.warning('数据未修改')
          return
        }
        res = await reqUpdateUser(formUser)
      }
      if (res?.code === 200) {
        ElMessage.success(action.value === 'add' ? '新增成功' : '编辑成功')
        getUserData()
        handleClose(formEl)
      } else {
        ElMessage.error('操作失败')
      }
      dialogVisible.value = false
    } else {
      console.log('error submit!!')
    }
  })
}
</script>

<template>
  <div class="user-view">
    <div class="header">
      <el-form inline>
        <el-form-item>
          <el-button type="success" style="margin-right: 550px" @click="addUserHandler">新增</el-button>
        </el-form-item>
        <el-form-item label="请输入">
          <el-input v-model="config.name" placeholder="请输入姓名关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUserData()">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" style="width: 100%" height="700">
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="age" label="年龄" width="80"></el-table-column>
      <el-table-column prop="sex" label="性别" width="80"></el-table-column>
      <el-table-column prop="birthday" label="出生年月" width="200"></el-table-column>
      <el-table-column prop="addr" label="住址" width="400"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="footer">
      <el-pagination
        layout="prev, pager, next"
        :total="tableCount"
        :page-size="15"
        :page-sizes="[10, 15, 20, 50]"
        @current-change="handleChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    width="43%"
    @close="handleClose(userForm)"
  >
    <el-form ref="userForm" :model="formUser" inline :rules="rules">
      <el-form-item label="姓名" prop="name"> <el-input v-model="formUser.name"></el-input> </el-form-item>
      <el-form-item label="年龄" prop="age"> <el-input v-model.number="formUser.age" type="number"></el-input> </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="formUser.sex">
          <el-radio :value="1">男</el-radio> <el-radio :value="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出生年月" prop="birthday">
        <el-date-picker v-model="formUser.birthday" type="date" placeholder="选择日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="住址" prop="addr"> <el-input v-model="formUser.addr"></el-input> </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit(userForm)">确定</el-button>
        <el-button @click="handleClose(userForm)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
.footer {
  margin-top: 7px;
}
</style>
